package com.ccx.library.handler.Log;

import com.ccx.library.exception.LogErrorException;
import com.ccx.library.function.annotation.Logger;
import com.ccx.library.function.source.SysLog;
import com.ccx.library.module.log.service.LogService;
import com.ccx.library.response.DataResponse;
import com.ccx.library.response.SimpleDataResponse;
import com.ccx.library.util.HttpUtils;
import com.ccx.library.util.JwtProvide;
import com.ccx.library.util.SnowflakeUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogHandler {

    @Autowired
    private LogService logService;

    DataResponse dataResponse=new SimpleDataResponse();

    @Pointcut("@annotation(com.ccx.library.function.annotation.Logger)")
    public void Logger(){
        log.info("log");
    }

    @Before("@annotation(Logger)")
    public void doAroundLog(JoinPoint joinPoint, Logger Logger) throws Throwable {
        HttpServletRequest request = HttpUtils.getRequest();
        /**
         * 逻辑
         */
        SysLog sysLog = new SysLog();
        sysLog.setLogId(String.valueOf(SnowflakeUtil.nextValue()));
        sysLog.setLogInfo(Logger.LogInfo());
        sysLog.setLogType(Logger.Type().getType());
        sysLog.setLogIpAddr(HttpUtils.getIpAddress(request));
        sysLog.setLogModule(Logger.Module().getModule());
        sysLog.setRequestUrl(request.getRequestURL().toString());
        sysLog.setLogTime(dataResponse.getTime());
        sysLog.setAuthor(getAuthor(request));
        Boolean save = logService.Save(sysLog);
        if (!save){
            throw new LogErrorException();
        }
    }

    public static String getAuthor(HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claim = JwtProvide.getTokenClaim(token);
        String username = (String) claim.get("username");
        return username;
    }
}
